# coding=utf-8
# author=haishan09@gmail.com
from django.conf.urls import url
from django.contrib import admin
from django.http import JsonResponse
from django.template.response import TemplateResponse
from django.contrib.auth import get_user_model
from treemenu.models import MenuItem, Menu
from treemenu.forms import MenuItemForm, MenuForm, MenuUserPermsAdminForm
from django.contrib.admin import helpers
from guardian.admin import GuardedModelAdmin

UserModel = get_user_model()

class MenuItemAdmin(GuardedModelAdmin):

    model = MenuItem
    readonly_fields  = ('level', 'rank')

    def get_form(self, *args, **kwargs):
        return MenuItemForm

    def get_urls(self):
        urls = super(MenuItemAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<menuitem_pk>[-\w]+)/flatten_children$', 
                self.admin_site.admin_view(self.get_flatten_children)),
            url(r'^api/add$', 
                self.admin_site.admin_view(self.api_add)),
            url(r'^(?P<menuitem_pk>[-\w]+)/api/change$', 
                self.admin_site.admin_view(self.api_change)),
            url(r'^(?P<menuitem_pk>[-\w]+)/api/delete$', 
                self.admin_site.admin_view(self.api_delete)),
            url(r'^(?P<menuitem_pk>[-\w]+)/api/move$', 
                self.admin_site.admin_view(self.api_move)),
            url(r'^(?P<menuitem_pk>[-\w]+)/api/assign_perm$', 
                self.admin_site.admin_view(self.api_assign_perm)),
            url(r'^(?P<menuitem_pk>[-\w]+)/api/remove_perm$', 
                self.admin_site.admin_view(self.api_remove_perm)),
        ]
        return my_urls + urls

    def get_flatten_children(self, request, menuitem_pk=None):
        root = MenuItem.objects.get(pk=menuitem_pk)
        user = None
        user_pk = request.GET.get('user')
        if user_pk:
            user = UserModel.objects.get(pk=user_pk)
            metadata = root.get_jstree_metadata_by_user(user=user)
        else:
            metadata = root.jstree_metadata
        return JsonResponse(metadata, safe=False)

    def api_add(self, request):
        label = request.POST.get('label')
        parent = request.POST.get('parent')
        obj = MenuItem(label=label, parent_id=parent)
        obj.save()
        return JsonResponse({'id': obj.pk})

    def api_change(self, request, menuitem_pk=None):
        obj = MenuItem.objects.get(pk=menuitem_pk)
        for k in request.POST:
            setattr(obj, k, request.POST.get(k))
        obj.save()
        return JsonResponse({'code': 0, 'message': 'ok'})

    def api_delete(self, request, menuitem_pk=None):
        obj = MenuItem.objects.get(pk=menuitem_pk)
        obj.delete()
        return JsonResponse({'code': 0, 'message': 'ok'})

    def api_move(self, request, menuitem_pk=None):
        obj = MenuItem.objects.get(pk=menuitem_pk)
        new_parent_pk = request.POST.get('parent')
        rank = int(request.POST.get('rank'))
        new_parent = MenuItem.objects.get(pk=new_parent_pk)
        obj.move_to(new_parent, rank)
        return JsonResponse({'code': 0, 'message': 'ok'})

    def api_assign_perm(self, request, menuitem_pk=None):
        obj = MenuItem.objects.get(pk=menuitem_pk)
        user = UserModel.objects.get(pk=request.POST.get('user'))
        obj.assign_perm('view_menuitem', user)
        return JsonResponse({'code': 0, 'message': 'ok'})

    def api_remove_perm(self, request, menuitem_pk=None):
        obj = MenuItem.objects.get(pk=menuitem_pk)
        user = UserModel.objects.get(pk=request.POST.get('user'))
        obj.remove_perm('view_menuitem', user)
        return JsonResponse({'code': 0, 'message': 'ok'})

class MenuAdmin(admin.ModelAdmin):

    model = Menu
    template = 'admin/treemenu/menu/change_form.html'

    def get_urls(self):
        urls = super(MenuAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<menu_pk>[-\w]+)/user/permissions/$', 
                self.admin_site.admin_view(self.change_user_permissions),
                name='permissions'),
        ]
        return my_urls + urls

    def change_user_permissions(self, request, menu_pk=None):
        obj = Menu.objects.get(pk=menu_pk)
        if request.method == 'POST':
            admin_form = MenuUserPermsAdminForm(request.POST, instance=obj)
            if admin_form.is_valid():
                user = UserModel.objects.get(pk=admin_form.cleaned_data['user'])
                menuitems = MenuItem.objects.filter(pk__in=admin_form.cleaned_data['checked_menuitems'].split(','))
                for menuitem in menuitems:
                    menuitem.assign_perm('view_menuitem', user)
        else:
            admin_form = MenuUserPermsAdminForm(instance=obj)
        context = {
            'change': True,
            'is_popup': False,
            'show_save': True,
            'save_as': False,
            'show_save_and_continue': True,
            'original': obj,
            'adminform': helpers.AdminForm(
                admin_form,
                [(None, {'fields': admin_form.fields})],
                self.get_prepopulated_fields(request, obj),
                ['menu', ],
                model_admin=self),
            'media': self.media,
            'app_label': self.model._meta.app_label,
            'opts': self.model._meta,
            'has_change_permission': self.has_change_permission(request, obj),
            'has_delete_permission': False,
            'has_add_permission': False,
            'title': '权限分配',
        }
        return TemplateResponse(request, 'admin/treemenu/menu/object_user_permissions.html', context)

    def get_form(self, *args, **kwargs):
        return MenuForm


admin.site.register(MenuItem, MenuItemAdmin)
admin.site.register(Menu, MenuAdmin)
